package com.iman.manjusri.repository.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.mongodb.WriteResult;
 
public abstract class MongoBaseDao<T> {
	private final Log log = LogFactory.getLog(this.getClass());
	/*private static ApplicationContext ctx = new GenericXmlApplicationContext(
			"spring/ApplicationContext-mongo-config.xml");
	private static MongoOperations mongoTemplate = (MongoOperations) ctx
			.getBean("mongoTemplate");*/
	@Autowired
	private MongoOperations mongoTemplate;

	public T save(T bean) {
		mongoTemplate.save(bean);
		return bean;
	}

	public void remove(T bean) {
		mongoTemplate.remove(bean);
	}

	public boolean updateFirst(Query query, Update update, T bean) {
		WriteResult result = mongoTemplate.updateFirst(query, update,
				bean.getClass());
		if (result.getError() == null) {
			return true;
		}
		log.error(result.getError());
		return false;
	}

	public boolean updateMulti(Query query, Update update) {
		WriteResult result = mongoTemplate.updateMulti(query, update,
				getEntityClass());
		if (result.getError() == null) {
			return true;
		}
		log.error(result.getError());
		return false;
	}

	public T findOne(Query query) {
		T bean = mongoTemplate.findOne(query, getEntityClass());
		return bean;
	}

	public List<T> find(Query query) {
		List<T> list = mongoTemplate.find(query, getEntityClass());
		return list;
	}
	
	public T findById(String id){
		return mongoTemplate.findById(id, getEntityClass());
	}


	abstract protected Class<T> getEntityClass();
}
